package com.sijibao.amap;

import android.content.Context;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.RouteSearch.DriveRouteQuery;
import com.amap.api.services.route.RouteSearch.OnRouteSearchListener;
import com.amap.api.services.route.WalkRouteResult;
import com.sijibao.amap.frg.AMapUtil;
import com.yicai.sijibao.utl.BusProvider;

/**
 * 计算两点间某条线路的真实距离默认为高德地图提供的第一条线路
 * @author licai
 *
 */
public class CalculateDistanceReal implements OnRouteSearchListener {

	private RouteSearch routeSearch;
	Context context;
	String sourceId;
	public CalculateDistanceReal(Context context,String sourceIds){
		this.context=context;
		this.sourceId=sourceIds;
		routeSearch = new RouteSearch(context);
		routeSearch.setRouteSearchListener(this);
	}
	
	public void calculateDistance(LatLng start,LatLng end){
		if(start==null||end==null){
			return;
		}
		LatLonPoint startPoint=new LatLonPoint(start.latitude, start.longitude);
		LatLonPoint endPoint=new LatLonPoint(end.latitude, end.longitude);
		final RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(
				startPoint, endPoint);
		// 驾车路径规划
		DriveRouteQuery query = new DriveRouteQuery(fromAndTo,
				RouteSearch.DrivingDefault, null, null, "");
		routeSearch.calculateDriveRouteAsyn(query);
	}

	@Override
	public void onBusRouteSearched(BusRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int arg1) {
		// TODO Auto-generated method stub
		if(result!=null){
			DrivePath drivePath = result.getPaths().get(0);
			double distance=drivePath.getDistance();
			BusProvider.getInstance().post(new DistanceEvent(distance, sourceId));
		}else{
			BusProvider.getInstance().post(new DistanceEvent(0, sourceId));
		}
		
	}

	@Override
	public void onWalkRouteSearched(WalkRouteResult arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 计算两点之间距离事件
	 * @author licai
	 *
	 */
	public  static class DistanceEvent{
		public double distance;
		public String sourceId;
		public DistanceEvent(double distance,String sourceId){
			this.distance=distance;
			this.sourceId=sourceId;
		}
	}
	public static double calculateDist(double lon1, double lat1,
			double lon2, double lat2)
	{
		double dis=AMapUtils.calculateLineDistance(new LatLng(lon1, lat1),new LatLng(lon2, lat2));
		return dis;
	}
}
